<template>
  <view class="container">
    <view class="card">
      <view class="avatar-row" v-if="user">
        <image class="avatar" :src="user.avatar_url || defaultAvatar.value" mode="aspectFill" />
        <view class="info">
          <text class="name">{{ user.nickname || "未设置昵称" }}</text>
          <text class="phone">{{ user.phone_number || "未绑定手机号" }}</text>
        </view>
      </view>

      <view v-else class="login-container">
        <view class="logo-section">
          <view class="logo-circle">
            <text class="logo-text">珠宝</text>
          </view>
        </view>
        <view class="button-section">
          <button class="login-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">手机号快捷登录</button>
          <button class="skip-btn" @tap="onSkipLogin">暂不登录</button>
        </view>
        <view class="terms-section">
          <view class="terms-notice">
            <text class="notice-text">请仔细阅读以下协议，了解我们如何收集、使用和保护您的信息</text>
          </view>
          <view class="terms-row" @tap="toggleAgreement">
            <view class="checkbox-container">
              <view class="checkbox" :class="{ checked: isAgreed }">
                <text class="checkmark" v-if="isAgreed">✓</text>
              </view>
            </view>
            <view class="terms-text-container">
              <text class="terms-text">
                我已仔细阅读并同意
                <text class="terms-link" @tap.stop="goToServiceTerms">《服务条款》</text>
                和
                <text class="terms-link" @tap.stop="goToPrivacyPolicy">《隐私政策》</text>
              </text>
              <text class="terms-hint">点击可查看完整协议内容</text>
            </view>
          </view>
          <view class="agreement-warning" v-if="!isAgreed">
            <text class="warning-text">⚠️ 需要同意协议才能继续登录</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="card" v-if="token">
      <view class="menu-section">
        <view class="menu-title">我的服务</view>
        <view class="menu-list">
          <view class="menu-item" @tap="goToOrders">
            <view class="menu-icon">📋</view>
            <text class="menu-text">我的订单</text>
            <text class="menu-arrow">></text>
          </view>
          <view class="menu-item" @tap="goToAddresses">
            <view class="menu-icon">📍</view>
            <text class="menu-text">收货地址</text>
            <text class="menu-arrow">></text>
          </view>
        </view>
      </view>
    </view>

    <view class="card" v-if="token">
      <button class="logout-btn" @tap="onLogout">退出登录</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue"
import { onShow } from "@dcloudio/uni-app"
import { post } from "../../utils/request.js"
import { getImageUrl } from "@/utils/imageConfig.js"

const token = ref("")
const user = ref(null)
const defaultAvatar = ref("/static/images/default-avatar.png")
const isAgreed = ref(false) // 用户需主动同意服务条款

function loadAuth() {
  try {
    token.value = uni.getStorageSync("mp_token") || ""
    const u = uni.getStorageSync("mp_user")
    user.value = u ? JSON.parse(u) : null
  } catch (_) {
    token.value = ""
    user.value = null
  }
}

onShow(async () => {
  loadAuth()
  await loadDefaultAvatar()
})

// 加载默认头像
async function loadDefaultAvatar() {
  try {
    const avatarUrl = await getImageUrl('profile_default_avatar', 'profile')
    defaultAvatar.value = avatarUrl
  } catch (error) {
    console.warn('加载默认头像失败:', error)
  }
}

async function onGetPhoneNumber(e) {
  console.log("onGetPhoneNumber 被调用", e)
  
  // 验证用户是否已同意服务条款和隐私政策
  if (!isAgreed.value) {
    uni.showToast({ 
      title: "请先阅读并同意《服务条款》和《隐私政策》", 
      icon: "none",
      duration: 3000
    })
    return
  }

  const detail = e?.detail || {}
  console.log("detail:", detail)

  if (!detail || !detail.code || !(detail.errMsg || "").endsWith("ok")) {
    console.log("手机号授权失败或取消")
    uni.showToast({ title: "未授权手机号", icon: "none" })
    return
  }

  const phoneCode = detail.code
  console.log("获取到 phoneCode:", phoneCode)

  try {
    uni.showLoading({ title: "登录中..." })

    // 获取登录凭证
    const loginRes = await uni.login({ provider: "weixin" })
    const loginCode = loginRes.code
    console.log("获取到 loginCode:", loginCode)

    // 调用后端接口
    console.log("调用登录接口...")
    const resp = await post("/wechat/phone-login", {
      loginCode,
      phoneCode,
      nickName: "微信用户",
      avatarUrl: "",
    })
    console.log("登录接口响应:", resp)

    const { token: tkn, user: usr } = resp.data || {}
    if (tkn && usr) {
      uni.setStorageSync("mp_token", tkn)
      uni.setStorageSync("mp_user", JSON.stringify(usr))
      loadAuth()
      uni.hideLoading()
      uni.showToast({ title: "登录成功", icon: "success" })
      
      // 检查是否需要跳转回原页面
      setTimeout(() => {
        handleLoginSuccess()
      }, 1500)
    } else {
      throw new Error("登录响应异常")
    }
  } catch (err) {
    console.error("登录失败", err)
    uni.hideLoading()
    uni.showToast({ title: err.message || "登录失败", icon: "none" })
  }
}

function onSkipLogin() {
  // 记录用户选择跳过登录
  try {
    uni.setStorageSync("mp_skip_login", "1")
  } catch {}
  uni.showToast({ title: "已暂不登录", icon: "none" })
}

function onLogout() {
  uni.removeStorageSync("mp_token")
  uni.removeStorageSync("mp_user")
  loadAuth()
  uni.showToast({ title: "已退出", icon: "none" })
}

// 切换同意状态
function toggleAgreement() {
  isAgreed.value = !isAgreed.value
}

// 跳转到服务条款页面
function goToServiceTerms() {
  uni.navigateTo({
    url: '/pages/policy/terms'
  })
}

// 跳转到隐私政策页面
function goToPrivacyPolicy() {
  uni.navigateTo({
    url: '/pages/policy/privacy'
  })
}

// 跳转到订单列表
function goToOrders() {
  uni.navigateTo({
    url: '/pages/order/list'
  })
}

// 跳转到地址管理
function goToAddresses() {
  uni.navigateTo({
    url: '/pages/address/list'
  })
}

// 处理登录成功后的跳转逻辑
function handleLoginSuccess() {
  try {
    const redirectUrl = uni.getStorageSync('mp_redirect_url')
    if (redirectUrl) {
      // 清除保存的跳转地址
      uni.removeStorageSync('mp_redirect_url')
      
      // 判断目标页面是否为tabBar页面
      const tabBarPages = [
        'pages/discover/discover',
        'pages/category/category', 
        'pages/appointment/appointment',
        'pages/cart/cart',
        'pages/cooperation/cooperation'
      ]
      
      // 从完整URL中提取页面路径
      const urlWithoutParams = redirectUrl.split('?')[0]
      const pagePath = urlWithoutParams.startsWith('/') ? urlWithoutParams.substring(1) : urlWithoutParams
      
      if (tabBarPages.includes(pagePath)) {
        // TabBar页面使用 switchTab
        uni.switchTab({
          url: redirectUrl,
          fail: (err) => {
            console.error('跳转TabBar页面失败:', err)
          }
        })
      } else {
        // 普通页面使用 navigateTo
        uni.navigateTo({
          url: redirectUrl,
          fail: (err) => {
            // 如果navigateTo失败，尝试使用reLaunch
            console.error('navigateTo失败，尝试使用reLaunch:', err)
            uni.reLaunch({
              url: redirectUrl
            })
          }
        })
      }
    }
  } catch (error) {
    console.error('处理登录成功跳转失败:', error)
  }
}
</script>

<style scoped>
.container {
  padding: 24rpx;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.card {
  background: #fff;
  border-radius: 16rpx;
  padding: 28rpx 24rpx;
  margin-bottom: 28rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.04);
}
.avatar-row {
  display: flex;
  align-items: center;
}
.avatar {
  width: 128rpx;
  height: 128rpx;
  border-radius: 50%;
  background: #f5f5f5;
}
.info {
  margin-left: 24rpx;
  display: flex;
  flex-direction: column;
}
.name {
  font-size: 32rpx;
  font-weight: 600;
}
.phone {
  font-size: 26rpx;
  color: #888;
  margin-top: 8rpx;
}
/* 登录容器 - 全屏布局 */
.login-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 0 60rpx;
  min-height: 80vh;
  background: #f5f5f5;
}

/* Logo区域 - 居中显示 */
.logo-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 50vh;
}

/* Logo圆形样式 - 绿色背景白色文字 */
.logo-circle {
  width: 200rpx;
  height: 200rpx;
  background: #2ecc71;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 32rpx rgba(46, 204, 113, 0.3);
}

.logo-text {
  color: white;
  font-size: 48rpx;
  font-weight: bold;
}

/* 按钮区域 */
.button-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  margin-bottom: 40rpx;
}

/* 登录按钮样式 */
.login-btn {
  width: 100%;
  background: #2ecc71;
  color: #fff;
  border: none;
  border-radius: 48rpx;
  padding: 24rpx 0;
  font-size: 32rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 24rpx rgba(46, 204, 113, 0.3);
  transition: all 0.3s ease;
}

.login-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(46, 204, 113, 0.3);
}

/* 跳过按钮样式 */
.skip-btn {
  width: 100%;
  background: transparent;
  color: #2ecc71;
  border: 4rpx solid #2ecc71;
  border-radius: 48rpx;
  padding: 20rpx 0;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.3s ease;
}

.skip-btn:active {
  background: rgba(46, 204, 113, 0.1);
}

/* 服务条款区域 */
.terms-section {
  width: 100%;
  padding-bottom: 40rpx;
}

.terms-notice {
  background: #f0f8ff;
  padding: 24rpx;
  border-radius: 12rpx;
  margin-bottom: 32rpx;
  border-left: 6rpx solid #2ecc71;
}

.notice-text {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
  text-align: justify;
}

.terms-row {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  padding: 24rpx;
  background: white;
  border-radius: 16rpx;
  border: 2rpx solid #e8e8e8;
  transition: all 0.3s ease;
}

.terms-row:active {
  background: #f8f9fa;
  border-color: #2ecc71;
}

.checkbox-container {
  margin-top: 6rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  transition: all 0.3s ease;
}

.checkbox.checked {
  background: #2ecc71;
  border-color: #2ecc71;
  transform: scale(1.1);
}

.checkmark {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.terms-text-container {
  flex: 1;
}

.terms-text {
  display: block;
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 8rpx;
}

.terms-hint {
  display: block;
  font-size: 22rpx;
  color: #999;
  line-height: 1.4;
}

.terms-link {
  color: #2ecc71;
  font-weight: 500;
  text-decoration: underline;
}

.agreement-warning {
  margin-top: 24rpx;
  padding: 16rpx 24rpx;
  background: #fff3cd;
  border: 2rpx solid #ffeaa7;
  border-radius: 12rpx;
  text-align: center;
}

.warning-text {
  font-size: 24rpx;
  color: #d63384;
  font-weight: 500;
}

/* 菜单样式 */
.menu-section {
  width: 100%;
}

.menu-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 24rpx;
}

.menu-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.menu-arrow {
  font-size: 24rpx;
  color: #999;
}

.logout-btn {
  width: 60%;
  display: block;
  margin: 0 auto;
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 16rpx;
  padding: 24rpx 0;
  box-shadow: 0 8rpx 20rpx rgba(245, 108, 108, 0.2);
}
</style>
